<template>
  <div class="app-container">
    <el-card shadow="never" style="padding:10px">
      <div style="padding-bottom: 10px">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handlerAdd">新增角色</el-button>
        <el-table
          :data="list"
          border
          fit
          highlight-current-row
          style="width:100%; margin-top:10px;"
        >
          <el-table-column type="index" :index="1" label="序号" width="150"></el-table-column>
          <el-table-column sortable prop="name" label="角色名" width="200"></el-table-column>
          <el-table-column sortable prop="description" label="描述"></el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="250">
            <template slot-scope="scope">
              <el-button @click="handlerPerm(scope.row.id)" type="text" size="small">分配权限</el-button>
              <el-button @click="handleUpdate(scope.row.id)" type="text" size="small">修改</el-button>
              <el-button @click="handleDelete(scope.row.id)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog title="编辑角色"  v-dialogDrag :visible.sync="roleFormVisible" style="hight:100px;line-height:1px">
      <el-form :model="formData" label-width="90px" style="margin-top:20px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.name" autocomplete="off" style="width:90%"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="formData.description" autocomplete="off" style="width:90%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      :title="'为【'+formData.name+'】分配权限'"
      :visible.sync="permFormVisible"
      style="hight:100px;line-height:1px"
    >
      <el-tree
        :data="treeData"
        check-strictly
        default-expand-all
        show-checkbox
        node-key="id"
        ref="tree"
        :default-checked-keys="checkNodes"
        :props="{label:'name'}"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignPrem">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import roleApi from "@/api/role";
import permissionApi from "@/api/permission";
import commonApi from "@/utils/common";

export default {
  data() {
    return {
      list: [],
      checkNodes: [],
      total: 0, //总记录数
      currentPage: 1, //当前页码
      pageSize: 5, //每页显示5条数据
      name: "",
      formData: {},
      treeData: [],
      roleFormVisible: false,
      permFormVisible: false
    };
  },

  created() {
    this.getList();
  },

  methods: {
    getList() {
      roleApi.getList(this.currentPage, this.pageSize, this.name).then(resp => {
        this.list = resp.data.rows;
        this.total = resp.data.total;
      });
    },

    handlerAdd() {
      this.formData = {};
      this.roleFormVisible = true;
    },
    handlerPerm(id) {
      roleApi.selectById(id).then(resp => {
        this.formData = resp.data.data;
        this.checkNodes = resp.data.data.permIds;
        permissionApi.getList('','').then(resp => {
          // console.log("权限：",resp.data);
          if(resp.data.code == 0) {
            this.treeData = commonApi.transformTozTreeFormat(resp.data.data);
            console.log("树：", this.treeData);
            // var newArr = [];
            // var item = '';
            // this.checkNodes.forEach(item => {
            //   this.filterFatherId(item,this.treeData,newArr);
            // })
            // this.checkNodes = newArr;
            // console.log("过滤后的id数组",this.checkNodes);
          }
          this.permFormVisible = true;
        });
      });
    },

    // 过滤父级id,思路：遍历treeData，将id与treeData中的id逐一比较，
    // 若相同，则判断这个id是否存在子级，不存在则将这个id并入新数组中，递归选择
    filterFatherId(id, data, newArr) {
      data.forEach(item => {
        // console.log(item)
        if (item.id == id) {
          if (item.children.length == 0) {
            newArr.push(item.id);
          }
        } else {
          if (item.children.length != 0) {
            this.filterFatherId(id, item.children, newArr);
          }
        }
      });
    },

    assignPrem() {
      // console.log(this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()));
      const pojo = {
        roleId: this.formData.id,
        // 包含父节点
        ids: this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys())
      };
      roleApi.assignPerm(pojo).then(resp => {
        if (resp.data.code == 0) {
          this.$message.success("分配权限成功");
          this.permFormVisible = false;
        } else {
          this.$message.error("分配权限成功");
        }
      });
    },

    handleUpdate(id) {
      roleApi.selectById(id).then(resp => {
        this.formData = resp.data.data;
        this.roleFormVisible = true;
      });
    },
    handleDelete(id) {
      if (id != null && id != "") {
        this.$confirm("此操作将永久删除该角色信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            roleApi.delete(id).then(resp => {
              if (resp.data.code == 0) {
                this.$message.success("删除角色成功");
                this.getList();
              } else {
                this.$message.error("删除角色失败");
                this.getList();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          message: "请选择需要删除的角色哦！",
          type: "warning"
        });
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange() {
      this.currentPage = val;
      this.getList();
    },

    saveOrUpdate() {
      if (this.formData.id == null || this.formData.id == undefined) {
        this.save();
      } else {
        this.update();
      }
    },

    // 角色保存
    save() {
      roleApi.save(this.formData).then(resp => {
        if (resp.data.code == 0) {
          this.$message.success("新增角色成功");
          this.formData = {};
          this.roleFormVisible = false;
          this.getList();
        } else {
          this.$message.error("新增角色失败");
          // this.formData = {};
          // this.roleFormVisible = false;
        }
      });
    },

    // 角色更新
    update() {
      roleApi.update(this.formData).then(resp => {
        if (resp.data.code == 0) {
          this.$message.success("更新角色成功");
          this.formData = {};
          this.roleFormVisible = false;
          this.getList();
        } else {
          this.$message.error("新增角色失败");
          // this.formData = {};
          // this.roleFormVisible = false;
        }
      });
    }
  }
};
</script>

<style lang="css" >
.el-dialog {
  max-height: calc(100% - 200px);
  /* max-height: 600px; */
  display: flex;
  flex-direction: column;
}
.el-dialog__body {
  overflow: auto;
}
</style>